package com.it.commicity.config.intercepter;


import com.it.commicity.common.ResultCodeEnum;
import com.it.commicity.config.exception.TokenException;
import com.it.commicity.domain.po.SysUser;
import com.it.commicity.utils.JwtUtils;
import com.it.commicity.utils.UserHolder;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("我是token拦截器-》" + request.getRequestURI());
        // 放行 OPTIONS 请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.err.println(HttpMethod.OPTIONS.toString());
            System.err.println(request.getMethod());
            return true;
        }
        //解析token
        SysUser user = JwtUtils.getMemberIdByJwtToken(request);
        if (user == null) {
            System.err.println("未登录");
            throw new TokenException(ResultCodeEnum.TOKEN_INVALID);
        }
        UserHolder.saveUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
